package cn.lisens.test.web;

import cn.lisens.test.entity.ExportData;
import cn.lisens.test.utils.JxlsExcelExportUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/export")
public class ExcelExportController {
    
    /**
     * 使用 JXLS2 导出员工数据为 Excel 文件
     * @return Excel 文件的字节流
     */
    @GetMapping("/employee/jxls")
    public ResponseEntity<byte[]> exportEmployeeDataWithJxls() {
        try {
            // 模拟测试数据
            List<ExportData> testData = generateTestData();
            
            // 获取当前时间
            String exportTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            
            // 使用 JXLS2 导出为 Excel
            byte[] excelBytes = JxlsExcelExportUtil.exportToExcel(
                "templates/employee-template.xlsx", 
                testData, 
                exportTime
            );
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", "员工数据_" + System.currentTimeMillis() + ".xlsx");
            
            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
    
    /**
     * 生成测试数据
     * @return 测试数据列表
     */
    private List<ExportData> generateTestData() {
        List<ExportData> dataList = new ArrayList<>();
        dataList.add(new ExportData("张三", 28, "zhangsan@example.com", "技术部", 12000.0));
        dataList.add(new ExportData("李四", 32, "lisi@example.com", "销售部", 10000.0));
        dataList.add(new ExportData("王五", 25, "wangwu@example.com", "人事部", 8000.0));
        dataList.add(new ExportData("赵六", 30, "zhaoliu@example.com", "财务部", 11000.0));
        dataList.add(new ExportData("钱七", 27, "qianqi@example.com", "市场部", 9500.0));
        dataList.add(new ExportData("孙八", 29, "sunba@example.com", "技术部", 13000.0));
        dataList.add(new ExportData("周九", 31, "zhoujiu@example.com", "运营部", 9000.0));
        dataList.add(new ExportData("吴十", 26, "wushi@example.com", "设计部", 8500.0));
        
        return dataList;
    }
}
